package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result QueryById(Long id) {

        //分布式锁解决缓存击穿
        //Shop shop = cacheClient.queryWithMutex(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //存入空值解决缓存穿透
        //Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //逻辑过期解决缓存击穿
        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if(shop == null){
            Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    private static final ExecutorService CACHE_REBUILD_EXECTUOR = Executors.newFixedThreadPool(10);

    /**
     * 逻辑过期解决缓存击穿
     * @param id
     * @return
     */
    public Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1. 读取 Redis 中的 JSON 字符串
        Object shop = redisTemplate.opsForValue().get(key);

        // 2. 判断是否命中
        if (shop == null ) {
            // 3. 未命中，返回空
            return null;
        }

        //3.命中

        //4.判断是否过期
        RedisData redisData = (RedisData) shop;
        //4.1未过期则返回店铺信息
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {

            return (Shop) redisData.getData();
        }

        //4.2过期则缓存重建

        //5.缓存重建
        String lockKey = LOCK_SHOP_KEY + id;
        //5.1获取互斥锁
        boolean lock = tryLock(lockKey);
        //5.2获取成功
        if (lock) {
            //5.3开启独立线程并返回店铺信息
            CACHE_REBUILD_EXECTUOR.submit(() -> {
                try {
                    this.saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //5.4释放互斥锁
                    unlock(lockKey);
                }
            });
        }
        //5.4获取失败，直接返回店铺信息

        return (Shop) shop;
    }
    /**
     * 分布式锁解决缓存击穿
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1. 读取 Redis 中的 JSON 字符串
        Object shop = redisTemplate.opsForValue().get(key);

        // 2. 判断是否存在
        if (shop != null) {
            // 3. 如果存在但为空值，则返回空
            if (shop instanceof String && ((String) shop).isEmpty()) {
                return null;
            }
            //否则直接返回店铺信息
            return (Shop) shop;
        }

        //3.实现缓存重建

        //3.1获取互斥锁
        Shop shopDB = null;
        String lockKey = LOCK_SHOP_KEY + id;
        try {
            boolean lock = tryLock(lockKey);
            //3.2判断是否获取成功
            if (!lock) {
                //3.3失败则休眠
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //3.4成功则查询数据库
            shopDB = getById(id);
            if (shopDB == null) {
                //返回空字符串，解决缓存穿透问题
                redisTemplate.opsForValue().set(key, "",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }

            // 4. 转 JSON 字符串并存入 Redis
            redisTemplate.opsForValue().set(key, shopDB,CACHE_SHOP_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //5.释放互斥锁
            unlock(lockKey);
        }
        return shopDB;
    }
    /**
     * 缓存穿透
     * @param id
     * @return
     */
    public Shop queryWhitPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 1. 读取 Redis 中的 JSON 字符串
        Object shop = redisTemplate.opsForValue().get(key);

        // 2. 判断是否存在
        if (shop != null) {
            if (shop instanceof String && ((String) shop).isEmpty()) {
                return null;
            }
            return (Shop) shop;
        }

        // 3. 数据库查询
        Shop shopDB = getById(id);
        if (shopDB == null) {
            //返回空字符串，解决缓存穿透问题
            redisTemplate.opsForValue().set(key, "",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        // 4. 转 JSON 字符串并存入 Redis
        redisTemplate.opsForValue().set(key, shopDB,CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shopDB;
    }


    /**
     * 加锁
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        // 1. 尝试加锁
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 解锁
     * @param key
     */
    private void unlock(String key) {
        // 2. 解锁
        redisTemplate.delete(key);
    }
    /**
     * 设置逻辑过期
     * @param
     */
    private void saveShop2Redis(Long id,Long expireTime){
        //查店铺数据
        Shop shop = getById(id);
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        //设置过期时间
        String key = CACHE_SHOP_KEY + id;
        //存入Redis
        redisTemplate.opsForValue().set(key, redisData);
    }

        @Override
    @Transactional
    public Result update(Shop shop) {

        //1.更新数据库
        Long id = shop.getId();
        if (id==null){
            return Result.fail("店铺id不能为空");
        }
        updateById(shop);
        //删除缓存
        redisTemplate.delete(CACHE_SHOP_KEY+id);
        return Result.ok();
    }
}
